'use strict';

/* Controllers */

angular.module('app')
    .controller('AppCtrl', ['toSave','$rootScope', 'test', '$scope', '$translate', '$localStorage', '$window', '$http',
        function (toSave,$rootScope, test, $scope, $translate, $localStorage, $window, $http) {
            Date.prototype.format = function(fmt) {
                var o = {
                    "M+" : this.getMonth()+1,                 //月份
                    "d+" : this.getDate(),                    //日
                    "h+" : this.getHours(),                   //小时
                    "m+" : this.getMinutes(),                 //分
                    "s+" : this.getSeconds(),                 //秒
                    "q+" : Math.floor((this.getMonth()+3)/3), //季度
                    "S"  : this.getMilliseconds()             //毫秒
                };
                if(/(y+)/.test(fmt)) {
                    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
                }
                for(var k in o) {
                    if(new RegExp("("+ k +")").test(fmt)){
                        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
                    }
                }
                return fmt;
            };
            localStorage.removeItem("page");
          localStorage.removeItem("lis");
          localStorage.removeItem('c');
          localStorage.removeItem('findname');
          // localStorage.clear($("input").eq(i).attr("id"));
            //setInterval(function(){
            //    console.log('aa')
            //},1000);
            toastr.options = {
                "closeButton": true,
                "debug": false,
                "progressBar": false,
                "positionClass": "toast-top-center",
                "onclick":null,
                "showDuration": "3000",
                "hideDuration": "1000",
                "timeOut": "5000",
                "extendedTimeOut": "1000",
                "showEasing": "swing",
                "hideEasing": "linear",
                "showMethod": "fadeIn",
                "hideMethod": "fadeOut"
            };
            $scope.defPageRows = 15;
            $scope.CommodityNameData = ["螺纹钢","线材","盘螺","钢坯"];
            $scope.OfficesData = [
                {
                    Name:"暂不选择",
                    Value:""
                },{
                    Name:"采购",
                    Value:"采购"
                },{
                    Name:"负责人",
                    Value:"负责人"
                }];
            $rootScope.$watch("myData", function (newValue, oldValue) {
                //console.log("我是控制器中的代码:" , newValue);
                //console.log("我是控制器中的代码:" , oldValue);
                //console.log($rootScope);
                //console.log($rootScope.myData);
                $scope.loadingShow = $rootScope.myData.loadingShow;
                //console.log("我是ng-if的值: " , $scope.loadingShow);
            });
            // add 'ie' classes to html
            var isIE = !!navigator.userAgent.match(/MSIE/i);
            isIE && angular.element($window.document.body).addClass('ie');
            isSmartDevice($window) && angular.element($window.document.body).addClass('smart');

            // config
            $scope.app = {
                name: '中伟钢物联',
                version: '1.0.0',
                // for chart colors
                color: {
                    primary: '#7266ba',
                    info: '#23b7e5',
                    success: '#27c24c',
                    warning: '#fad733',
                    danger: '#f05050',
                    light: '#e8eff0',
                    dark: '#3a3f51',
                    black: '#1c2b36'
                },
                settings: {
                    themeID: 8,
                    navbarHeaderColor: 'bg-info dker',
                    navbarCollapseColor: 'bg-info dker',
                    asideColor: 'bg-light dker b-r',
                    headerFixed: true,
                    asideFixed: true,
                    asideFolded: false,
                    asideDock: false,
                    container: false
                }
            };

            // save settings to local storage
            if (angular.isDefined($localStorage.settings)) {
                $scope.app.settings = $localStorage.settings;
            } else {
                $localStorage.settings = $scope.app.settings;
            }
            $scope.$watch('app.settings', function () {
                if ($scope.app.settings.asideDock && $scope.app.settings.asideFixed) {
                    // aside dock and fixed must set the header fixed.
                    $scope.app.settings.headerFixed = true;
                }
                // save to local storage
                $localStorage.settings = $scope.app.settings;
            }, true);

            // angular translate
            $scope.lang = { isopen: false };
            $scope.langs = { en: 'English', de_DE: 'German', it_IT: 'Italian' };
            $scope.selectLang = $scope.langs[$translate.proposedLanguage()] || "English";
            $scope.setLang = function (langKey, $event) {
                // set the current lang
                $scope.selectLang = $scope.langs[langKey];
                // You can change the language during runtime
                $translate.use(langKey);
                $scope.lang.isopen = !$scope.lang.isopen;
            };
            function isSmartDevice($window) {
                // Adapted from http://www.detectmobilebrowsers.com
                var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
                // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
                return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
            }
           
            //$scope.isreturn = false;
            function AnalogLogin(u,p){
                var isreturn = false;
                $.ajax({
                    type: "Get",
                    url: "/api/Login",
                    data: { loginName: u, md5Pw: p, salt: "" },
                    async: false,
                    success: function(data) {
                        if(data.State <= 0){
                            isreturn = false;
                        }else if (data.State > 0){
                            sessionStorage.setItem("user",JSON.stringify(data.Data));
                            isreturn = true;
                            shuaxinfunction();
                        }else{
                            isreturn = false;
                        }
                    }
                });
                return isreturn;
            }

            if(typeof (javatojs) != 'undefined'){
                $scope.equipment = javatojs;
            }
            var shuaxinfunction = function() {
                $scope.user = JSON.parse(sessionStorage.getItem("user"));
                $scope.Jurisdiction = $scope.user.Roles;
                window.Jurisdiction = $scope.user.Roles;
                //退出登录
                $scope.logout = function () {
                    console.log("退出");
                    sessionStorage.removeItem("user");
                    sessionStorage.removeItem("username");
                    if (typeof (window.webkit) != 'undefined') {
                        window.webkit.messageHandlers.removeItem.postMessage(null);
                    }
                    ZhdApi.removeItem("username");
                    ZhdApi.removeItem("password");
                    $http({
                        method: 'post',
                        url: '../api/Employee/OutLogin'
                    }).success(function (req) {
                        location.href = "../../Home/Login";
                    });
                };
            };
            if (sessionStorage.getItem("user")) {
                shuaxinfunction();
            } else {
                if(AnalogLogin(ZhdApi.getItem("username"),ZhdApi.getItem("password"))){
                    //location.reload(false);
                }else{
                    alert("没有登陆权限,请重新登录");
                    location.href = "../../Home/Login";
                    }
                }
            if(!sessionStorage.getItem("districts")){
                //获取地市
                $http({
                    url: "/api/District",
                    method: "GET"
                })
                .then(function(res) {
                        window.localStorage.setItem("districts",JSON.stringify(res.data));
                })
                    .then(function(error) {
                        if (error) {
                            console.log("error");
                        }
                    });
            }
        }])

    //我的计划单列表控制器
    //.controller("MyorderListC" , function($scope,$state,$http){
    //    $scope.page = 1;
    //    $scope.rows = 10;
    //    //请求数据
    //    $http({
    //        url:"../api/Order/List?page="+$scope.page+"&rows="+$scope.rows,
    //        method:"GET"
    //    })
    //        .then(function (res) {
    //            $scope.orders = res.data.Data;
    //        })
    //        .then(function (error) {
    //            if(error){
    //                console.log("error");
    //            }
    //        });
    //    $scope.xxx = function (index) {
    //        $state.go('app.Order_MyDetail',{
    //            orderid:JSON.stringify($scope.orders[index].Id)
    //        });
    //    }
    //    $scope.add = function(index){
    //        $state.go('app.Order_Add');
    //    };
    //    $scope.find = function (index) {
    //        $state.go('app.Order_Add');
    //    };
    //})

    //客户信息表控制器
    .controller("tablesC", function ($scope, $state, $stateParams, $http) {
        $scope.page = 1;
        $scope.rows = 10;
        $http({
            url: "http://115.28.104.1:8050/api/Values/xxzx?page=" + $scope.page + "&rows=" + $scope.rows,
            method: "GET"
        })
            .then(function (res) {
                $scope.pageid = res.data.Page;
                $scope.total = parseInt(res.data.Total / $scope.rows);
                $scope.users = res.data.Data;
            })
            .then(function (error) {
                if (error) {
                    console.log("error");
                }
            });
        $scope.next = function (page) {
            $scope.nextid = page + 1;
            $http({
                url: "http://115.28.104.1:8050/api/Values/xxzx?page=" + $scope.nextid + "&rows=" + $scope.rows,
                method: "GET"
            })
                .then(function (res) {
                    $scope.pageid = res.data.Page;
                    $scope.total = parseInt(res.data.Total / $scope.rows);
                    $scope.users = res.data.Data;
                })
                .then(function (error) {
                    if (error) {
                        console.log("error");
                    }
                });
        };
        $scope.previous = function (page) {
            $scope.previousid = page - 1;
            $http({
                url: "http://115.28.104.1:8050/api/Values/xxzx?page=" + $scope.previousid + "&rows=" + $scope.rows,
                method: "GET"
            })
                .then(function (res) {
                    $scope.pageid = res.data.Page;
                    $scope.total = parseInt(res.data.Total / $scope.rows);
                    $scope.users = res.data.Data;
                })
                .then(function (error) {
                    if (error) {
                        console.log("error");
                    }
                });
        }
    }) 
            //时间控件
             
    .controller("buildjihuadanC", function ($scope) {

    })